package com.example.demo.arithmetic.datastructure.tree;


public class Leetcode98_3 {


    public boolean isValidBST(TreeNode root) {
        return doValid(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    /**
     * 上下限判断是否是合法的二叉树
     *
     * @param node
     * @param min  下限
     * @param max  上限
     * @return
     */
    private boolean doValid(TreeNode node, long min, long max) {
        if (node == null) {
            return true;
        }
        if (node.val <= min || node.val >= max) {
            return false;
        }
        return doValid(node.left, min, node.val) && doValid(node.right, node.val, max);
    }

    // 示例使用  
    public static void main(String[] args) {
        // 构造一个简单的BST进行测试  
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.right = new TreeNode(5);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);

        Leetcode98_3 traversal = new Leetcode98_3();
        System.out.println(traversal.isValidBST(root));
    }
}